package stock.netfonds;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import misc.Helpers;

import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;

import static java.util.Calendar.*;

import stock.NetfondsSale;

import ernie.database.NetfondsWebMysql;

public class NetFondsParser implements Runnable {
	private final static String BASE_URL = "http://hopey.netfonds.no/tradedump.php?date=%s&paper=%s&csv_format=txt";
	private static NetfondsWebMysql db = new NetfondsWebMysql("127.0.0.1", "netfonds");

	public static void main(String[] args) {
		new NetFondsParser().run();
	}

	public void run() {
		Timer timer = new Timer();
		 TimerTask task = new TimerTask() {
			@Override
			public void run() {
				db.saveEntries(getNetFondSales("ERIC-B.ST"));
				db.saveEntries(getNetFondSales("NOKI-SEK.ST"));
				db.saveEntries(getNetFondSales("VOLV-B.ST"));
			}
		};
		
		// For testing:
        //task.run();

        Calendar nextTrigger = Calendar.getInstance();
        nextTrigger.set(Calendar.HOUR_OF_DAY, 20);
        if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 20) {
            nextTrigger.add(Calendar.DAY_OF_MONTH, 1);
        }
        timer.schedule(task, new Date(nextTrigger.getTimeInMillis() + 2000),
                1000 * 3600 * 24);
	}

	private static List<NetfondsSale> getNetFondSales(String name) {
		List<NetfondsSale> sales = new ArrayList<>();
		System.out.println("Fetching netfond sales page for " + name + "...");

		Long latestms = db.getLatestTime(name);
		Calendar latest = Calendar.getInstance();
		latest.setTimeInMillis(latestms);

		Calendar currentDate = Calendar.getInstance();
		currentDate.set(HOUR_OF_DAY, 17);
		for (int i=0; i <= 20; i++) {
			double millisSinceLast = currentDate.getTimeInMillis() - latest.getTimeInMillis();
			if (millisSinceLast >= 1000*3600*12 && currentDate.get(DAY_OF_WEEK) != SATURDAY && currentDate.get(DAY_OF_WEEK) != SUNDAY) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String currentDate_S = sdf.format(currentDate.getTime());

				String url = String.format(BASE_URL, currentDate_S, name);
				String page = getPage(url).getContent();

				Scanner scanner = new Scanner(page);
				scanner.nextLine();//Skip first line
				while (scanner.hasNextLine()) {
					String line = scanner.nextLine();
					String[] lineArray = line.split("\\s+");
					if (!lineArray[3].equals("U")) { //U are not real trades
						String date_S = lineArray[0];
						Date date = null;
						SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
						try {
							date = formatter.parse(date_S);
						} catch (ParseException e) {
							e.printStackTrace();
						}
						long time = date.getTime();
						double price = Double.parseDouble(lineArray[1]);
						long amount = Long.parseLong(lineArray[2]);
						String buyer = null;
						String seller = null;
						try {
							buyer = lineArray[5];
						} catch (Exception e) {}
						try {
							seller = lineArray[6];
						} catch (Exception e) {}

						NetfondsSale sale = new NetfondsSale(time, name, price, amount, buyer, seller);
						sales.add(sale);
					}
				}
				scanner.close();
			}
			currentDate.add(Calendar.DATE, -1);
		}
		System.out.println("Saving " + sales.size() + " netfond sales for " + name);
		return sales;
	}

	private static TextPage getPage(String url) {
		WebClient client = Helpers.createNewAndSilenceWebClient();
		try {
			return (TextPage) client.getPage(url);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			return getPage(url);
		}
	}

}
